package com.ruoyi.jihuo.service.handler;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.jihuo.domain.JhTmGoods;
import com.ruoyi.jihuo.service.IJhTmProductsOnSaleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class PriorityHandlerChain {

    @Autowired
    private IJhTmProductsOnSaleService jhTmProductsOnSaleService;

    private final List<com.ruoyi.jihuo.service.handler.PriorityHandler> handlers;

    // Spring 自动注入所有 PriorityHandler 实现类，并按优先级排序
    @Autowired
    public PriorityHandlerChain(List<com.ruoyi.jihuo.service.handler.PriorityHandler> handlers) {
        this.handlers = handlers.stream()
                .sorted(Comparator.comparingInt(com.ruoyi.jihuo.service.handler.PriorityHandler::getPriority))
                .collect(Collectors.toList());
    }

    /**
     * 正常处理的商品数据 处理器返回true或false(如过滤掉的),异常数据需要子处理器向上抛出异常,由此方法调用处进行异常处理
     * 通过ProcessContext.errorInfo记录商品上架异常的详细信息
     * @param request
     */
    public void handleRequest(ProcessContext<JSONObject> request) {
        JhTmGoods item = request.getData().getObject("item", JhTmGoods.class);
        for (PriorityHandler handler : handlers) {
            try {
                log.info("源商品ID:{},开始执行:{}",item.getJhItemId(),handler.getClass().getName());
                boolean result = handler.handle(request);
                if (!result) {
                    break;
                }
                log.info("源商品ID:{},执行结束:{}",item.getJhItemId(),handler.getClass().getName());
            }catch (Exception e){
                throw new RuntimeException(e);
            }
        }
    }
}